"""
数据存储模块
负责人脸特征数据的持久化存储
"""

import json
import numpy as np
import os
from typing import Dict, Any


def save_face_database(face_database: Dict[str, Any], file_path: str) -> bool:
    """
    保存人脸数据库到文件
    :param face_database: 人脸数据库
    :param file_path: 保存文件路径
    :return: 是否保存成功
    """
    try:
        # 确保目录存在
        directory = os.path.dirname(file_path)
        if directory and not os.path.exists(directory):
            os.makedirs(directory)
        
        # 将numpy数组转换为列表以便JSON序列化
        serializable_database = {}
        for name, data in face_database.items():
            if isinstance(data, dict) and "encodings" in data:
                # 新的多图片数据结构
                serializable_database[name] = {
                    "encodings": []
                }
                for face_info in data["encodings"]:
                    serializable_database[name]["encodings"].append({
                        "id": face_info["id"],
                        "encoding": face_info["encoding"].tolist() if isinstance(face_info["encoding"], np.ndarray) else face_info["encoding"],
                        "image_path": face_info["image_path"]
                    })
            elif isinstance(data, dict) and "encoding" in data:
                # 旧的单图片数据结构，转换为新的结构
                serializable_database[name] = {
                    "encodings": [{
                        "id": f"{name}_face_0",
                        "encoding": data["encoding"].tolist() if isinstance(data["encoding"], np.ndarray) else data["encoding"],
                        "image_path": data["image_path"]
                    }]
                }
            else:
                # 最老的数据结构，转换为新的结构
                serializable_database[name] = {
                    "encodings": [{
                        "id": f"{name}_face_0",
                        "encoding": data.tolist() if isinstance(data, np.ndarray) else data,
                        "image_path": ""
                    }]
                }
        
        # 保存到JSON文件
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(serializable_database, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存人脸数据库失败: {e}")
        return False


def load_face_database(file_path: str) -> Dict[str, Any]:
    """
    从文件加载人脸数据库
    :param file_path: 文件路径
    :return: 人脸数据库
    """
    try:
        if not os.path.exists(file_path):
            print(f"数据库文件不存在: {file_path}")
            return {}
        
        # 从JSON文件加载
        with open(file_path, 'r', encoding='utf-8') as f:
            serializable_database = json.load(f)
        
        # 将列表转换回numpy数组
        face_database = {}
        for name, data in serializable_database.items():
            if isinstance(data, dict) and "encodings" in data:
                # 新的多图片数据结构
                face_database[name] = {
                    "encodings": []
                }
                for face_info in data["encodings"]:
                    face_database[name]["encodings"].append({
                        "id": face_info["id"],
                        "encoding": np.array(face_info["encoding"]) if isinstance(face_info["encoding"], list) else face_info["encoding"],
                        "image_path": face_info["image_path"]
                    })
            elif isinstance(data, dict) and "encoding" in data:
                # 旧的单图片数据结构
                face_database[name] = {
                    "encodings": [{
                        "id": f"{name}_face_0",
                        "encoding": np.array(data["encoding"]) if isinstance(data["encoding"], list) else data["encoding"],
                        "image_path": data["image_path"]
                    }]
                }
            else:
                # 最老的数据结构
                face_database[name] = {
                    "encodings": [{
                        "id": f"{name}_face_0",
                        "encoding": np.array(data) if isinstance(data, list) else data,
                        "image_path": ""
                    }]
                }
        
        return face_database
    except Exception as e:
        print(f"加载人脸数据库失败: {e}")
        return {}